package bll

import (
	"context"
	"gorm.io/gorm"
	log "manager/collector/logger"
	"manager/errors"
	"manager/utils"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"

	"manager/auth"
)

type userSetting struct {
	iUserSetting store.IUserSetting
}

var UserSetting = &userSetting{
	iUserSetting: postgres.UserSetting,
}

func (a *userSetting) init() func() {
	return func() {}
}

func (a *userSetting) onEvent(data *event.Data) {
	if data == nil || data.Type != event.Event_User_Reg {
		return
	}

	log.Info("---------------- userSetting onEvent data:", utils.ToJsonString(data))

	// 解析参数
	obj := data.Data.(*event.UserReg)
	if obj == nil {
		log.Error("userSetting onEvent err")
		return
	}

	// 创建用户设置
	err := a.Create(context.Background(), &model.UserSettingCreateRequest{
		UserId:        obj.UserId,
		Vibration:     1,
		CutPower:      1,
		ChargeMonitor: 1,
		GuardAlarm:    1,
		FaultAlarm:    1,
	})
	if err != nil {
		log.Errorf("userSetting onEvent Create err", err)
		return
	}
}

// Create 创建
func (a *userSetting) Create(ctx context.Context, in *model.UserSettingCreateRequest) error {
	var (
		err error
	)

	// 获取用户Id
	if in.UserId == 0 {
		in.UserId, _ = auth.ContextUserID(ctx)
	}

	if in.UserId == 0 {
		return errors.ParameterErr.Error()
	}

	// todo: 查看是否创建过设置
	settings, err := a.iUserSetting.Find(ctx, &model.UserSettingInfoRequest{
		UserId: &in.UserId,
	})

	if settings != nil && err == nil {
		log.Warnf("userSetting Create recode exist UserId:%v", in.UserId)
		return nil
	}

	// 构建创建现场数据
	c := buildUserSetting(in)
	_, err = a.iUserSetting.Create(ctx, c)
	return err
}

// Update 更新
func (a *userSetting) Update(ctx context.Context, in *model.UserSettingUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.UserId == nil {
		userId, _ := auth.ContextUserID(ctx)
		in.UserId = &userId
	}

	if *in.UserId == 0 {
		return errors.New("userid is illegal")
	}

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.Face != nil {
		dict["face"] = in.Face
	}

	if in.Fingerprint != nil {
		dict["fingerprint"] = in.Fingerprint
	}

	if in.Vibration != nil {
		dict["vibration"] = in.Vibration
	}

	if in.CutPower != nil {
		dict["cut_power"] = in.CutPower
	}

	if in.ChargeMonitor != nil {
		dict["charge_monitor"] = in.ChargeMonitor
	}

	if in.GuardAlarm != nil {
		dict["guard_alarm"] = in.GuardAlarm
	}

	if in.FaultAlarm != nil {
		dict["fault_alarm"] = in.FaultAlarm
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iUserSetting.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *userSetting) Delete(ctx context.Context, in *model.UserSettingDeleteRequest) error {
	return a.iUserSetting.Delete(ctx, in.Id)
}

// List 列表查询
func (a *userSetting) List(ctx context.Context, in *model.UserSettingListRequest) (*model.UserSettingListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.UserSetting
		out   = &model.UserSettingListResponse{}
	)

	if total, list, err = a.iUserSetting.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.UserSettingsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *userSetting) Find(ctx context.Context, in *model.UserSettingInfoRequest) (*model.UserSettingInfo, error) {
	var (
		err  error
		data *entity.UserSetting
		out  = &model.UserSettingInfo{}
	)

	if in.UserId == nil {
		userId, _ := auth.ContextUserID(ctx)
		in.UserId = &userId
	}

	if data, err = a.iUserSetting.Find(ctx, in); err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	// todo: 临时这么设计，查询不存在的时候创建设置
	if err == gorm.ErrRecordNotFound {
		// 用户注册事件
		userId, _ := auth.ContextUserID(ctx)
		event.Emit(&event.Data{
			Type: event.Event_User_Reg,
			Data: &event.UserReg{
				UserId: userId,
			},
		})

		// 再次查询
		if data, err = a.iUserSetting.Find(ctx, in); err != nil {
			return nil, err
		}

	}

	out = model.UserSettingEntityToDto(data)
	return out, nil
}

// buildUserSetting 构建创建数据现场
func buildUserSetting(in *model.UserSettingCreateRequest) *entity.UserSetting {
	// todo: check the entity is required
	return &entity.UserSetting{

		UserId: in.UserId,

		Face: in.Face,

		Fingerprint: in.Fingerprint,

		Vibration: in.Vibration,

		CutPower: in.CutPower,

		ChargeMonitor: in.ChargeMonitor,

		GuardAlarm: in.GuardAlarm,

		FaultAlarm: in.FaultAlarm,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
